﻿using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using Microsoft.Extensions.DependencyInjection;
using System.Windows.Media;
using VIA.Foundation;
using VIA.Integration;
using VIA.Integration.Domain;
using VIA.Integration.Domain.Production;
using VIA.Presentation;
using VIA.Presentation.Contracts;
using VIA.Project.Domain.Services;
using VIA.SiMoJi.Domain.Inspection;
using VIA.SiMoJi.Domain.Electronics;
using VIA.SiMoJi.Domain.Option;
using VIA.SiMoJi.Domain.Vision;
using PropertyChanged;
using System.Collections.ObjectModel;
using VIA.Integration.Presentation;
using VIA.Integration.Presentation.View;
using Autofac.Core;
using OpenCvSharp;
using VIA.SiMoJi.Domain;
using VIA.SiMoJi.Presentation;
using VIA.RbacPassport;
using VIA.Presentation.Services;
using Microsoft.Extensions.Logging;

namespace VIA.Project.Presentation.ViewModel.Inspection
{
    public record LogGroup(string Name, string Category);

    [ViewModel(typeof(IHomeView))]
    internal class HomeViewModel : ViewModel<IHomeView>
    {
        ~HomeViewModel()
        {
            _refreshCts?.Cancel();
        }
        #region Filed
        private readonly IOptionRepository _optionRepository;
        private readonly IServiceProvider _service;
        private readonly ICommandFactory _commandFactory;
        private readonly IDispatcherService _dispatcher;
        private readonly IApplicationLog _applicationLog;
        private readonly IAutoDeleteImage _autoDeleteImage;
        private readonly IProductionLine _productionLine;
        //private InspectorOption _inspectorOption;
        private readonly Inspector _inspector;
        readonly IMessageService _messageService;
        readonly IShellService _shellService;

        private ObservableValue _okValue = new ObservableValue(0);
        private ObservableValue _ngValue = new ObservableValue(0);
        private TrayPointStatus nozzelStatus1;
        private TrayPointStatus nozzelStatus2;
        private TrayPointStatus nozzelStatus3;
        private TrayPointStatus nozzelStatus4;
        private TrayPointStatus nozzelStatus5;
        private TrayPointStatus nozzelStatus6;
        private TrayPointStatus nozzelStatus7;
        private bool hasFeedTray;
        private string gongLiaoStep = "未初始化";
        private string siMoStep = "未初始化";
        private string banYunStep = "未初始化";
        private bool isDoorAlarm;
        private int ngTrayStatus;
        private CancellationTokenSource _refreshCts;
        private bool isFeed1Ready;
        private bool isFeed2Ready;
        private bool isLightOn;
        private int currentCol;
        private DateTime _startRunningTime;
        private TimeSpan _runningTimeSpan;
        private string runTimeRecord;
        private bool isDryRunMode;
        private bool isDoor1Closed;
        private bool isDoor2Closed;
        private int productCount;
        private bool isOperateEnable;
        private ImageResultMode selectedImageResultModle;
        private double _currentCT;
        private double _currentUPH;
        private EquipmentRunningStateModel _eqpRunningStateModel;
        private ICurrentUser _currentUser;
        private bool hasHomeviewOprateRight;
        private bool isManualMode = true;
        private bool isSetFeedTrayEnable;
        #endregion

        #region Command
        public IRelayCommand ClearLogCommand { get; }
        public IRelayCommand ClearProductRecordCommand { get; }
        public IRelayCommand ClearNozzeStatusCommand1 { get; }
        public IRelayCommand ClearNozzeStatusCommand2 { get; }
        public IRelayCommand ClearNozzeStatusCommand3 { get; }
        public IRelayCommand ClearNozzeStatusCommand4 { get; }
        public IRelayCommand ClearNozzeStatusCommand5 { get; }
        public IRelayCommand ClearNozzeStatusCommand6 { get; }
        public IRelayCommand ClearNozzeStatusCommand7 { get; }
        public IRelayCommand ClearGongLiaoZaiJiCommand { get; }
        public IRelayCommand ClearNGTrayCommand { get; }
        public IRelayCommand ClearFeedTrayCommand { get; }
        public IRelayCommand OpenLightCommand { get; }
        public IRelayCommand ClearRunningTimeCommand { get; }
        public IRelayCommand TestCommand { get; }
        public IRelayCommand OpenSaveDoor1Command { get; }
        public IRelayCommand OpenSaveDoor2Command { get; }

        #endregion

        #region Property
        public List<LogGroup> LogGroups { get; private set; } = new();
        public TrayPointStatus NozzelStatus1 { get => nozzelStatus1; set => SetProperty(ref nozzelStatus1, value); }
        public TrayPointStatus NozzelStatus2 { get => nozzelStatus2; set => SetProperty(ref nozzelStatus2, value); }
        public TrayPointStatus NozzelStatus3 { get => nozzelStatus3; set => SetProperty(ref nozzelStatus3, value); }
        public TrayPointStatus NozzelStatus4 { get => nozzelStatus4; set => SetProperty(ref nozzelStatus4, value); }
        public TrayPointStatus NozzelStatus5 { get => nozzelStatus5; set => SetProperty(ref nozzelStatus5, value); }
        public TrayPointStatus NozzelStatus6 { get => nozzelStatus6; set => SetProperty(ref nozzelStatus6, value); }
        public TrayPointStatus NozzelStatus7 { get => nozzelStatus7; set => SetProperty(ref nozzelStatus7, value); }
        public bool HasFeedTray { get => hasFeedTray; set => SetProperty(ref hasFeedTray, value); }
        public int NGTrayStatus { get => ngTrayStatus; set => SetProperty(ref ngTrayStatus, value); }
        public bool IsFeed1Ready { get => isFeed1Ready; set => SetProperty(ref isFeed1Ready, value); }
        public bool IsFeed2Ready { get => isFeed2Ready; set => SetProperty(ref isFeed2Ready, value); }
        public bool IsDoor1Closed { get => isDoor1Closed; set => SetProperty(ref isDoor1Closed, value); }
        public bool IsDoor2Closed { get => isDoor2Closed; set => SetProperty(ref isDoor2Closed, value); }
        public SeriesCollection YieldSeries { get; private set; }
        public double Yield
        {
            get
            {
                var total = _ngValue.Value + _okValue.Value;
                if (total == 0)
                    return 0;
                return _okValue.Value / total;
            }
        }
        public int ProductCount { get => productCount; set => SetProperty(ref productCount, value); }
        public ObservableCollection<ImageResultMode> Results { get; set; } = new ObservableCollection<ImageResultMode>();
        public ObservableCollection<FeedTrayColunm> FeedTrayColunms { get; set; } = new ObservableCollection<FeedTrayColunm>();
        public ObservableCollection<NGTrayRow> NGTrayRows { get; set; } = new ObservableCollection<NGTrayRow>();
        public ImageResultMode SelectedImageResultModle { get => selectedImageResultModle; set => SetProperty(ref selectedImageResultModle, value); }
        public string GongLiaoStep { get => gongLiaoStep; set => SetProperty(ref gongLiaoStep, value); }
        public string BanYunStep { get => banYunStep; set => SetProperty(ref banYunStep, value); }
        public string SiMoStep { get => siMoStep; set => SetProperty(ref siMoStep, value); }
        public bool IsDoorAlarm { get => isDoorAlarm; set => SetProperty(ref isDoorAlarm, value); }
        public bool IsLightOn { get => isLightOn; private set => SetProperty(ref isLightOn, value); }
        public int CurrentCol { get => currentCol; set { SetProperty(ref currentCol, value); } }
        public string RunTimeRecord { get => runTimeRecord; private set => SetProperty(ref runTimeRecord, value); }
        public bool IsDryRunMode { get => isDryRunMode; set => SetProperty(ref isDryRunMode, value); }
        public bool IsOperateEnable { get => isOperateEnable; set => SetProperty(ref isOperateEnable, value); }
        public bool HasHomeviewOprateRight { get => hasHomeviewOprateRight; set => SetProperty(ref hasHomeviewOprateRight, value); }
        public bool IsManualMode { get => isManualMode; set => SetProperty(ref isManualMode, value); }
        public bool IsSetFeedTrayEnable { get => isSetFeedTrayEnable; set => SetProperty(ref isSetFeedTrayEnable, value); }
        /// <summary>
        /// 力矩值列表
        /// </summary>
        public ObservableCollection<LijuModel> LijuModels { get; set; } = new ObservableCollection<LijuModel>();
        public double CurrentCT
        {
            get => _currentCT;
            set => SetProperty(ref _currentCT, value);
        }
        public double CurrentUPH
        {
            get => _currentUPH;
            set => SetProperty(ref _currentUPH, value);
        }

        public EquipmentRunningStateModel EqpRunningStateModel
        {
            get => _eqpRunningStateModel;
            set => SetProperty(ref _eqpRunningStateModel, value);
        }
        #endregion

        readonly ICalcTimeService _calcTimeService;
        public HomeViewModel(IOptionRepository optionRepository, IServiceProvider service, ICommandFactory commandFactory, IDispatcherService dispatcherService, IShiftService shiftService, IApplicationLog applicationLog, IAutoDeleteImage autoDeleteImage, Inspector inspector)
        {
            this._optionRepository = optionRepository;
            _service = service;
            _commandFactory = commandFactory;
            _dispatcher = dispatcherService;
            _applicationLog = applicationLog;
            _autoDeleteImage = autoDeleteImage;
            _eqpRunningStateModel = new EquipmentRunningStateModel(service);
            _inspector = inspector;
            _inspector.StatusChanged += Inspector_StatusChanged;
            _inspector.ManualAutoStateChanged += Inspector_ManualAutoStateChanged;
            _currentUser = service.GetService<ICurrentUser>();
            _currentUser.UserChanged += CurrentUser_UserChanged;
            _inspector.GongLiaoStation.StepsChanged += GongLiaoStation_StepChanged;
            _inspector.GongLiaoStation.ManualStepsConfirmChanged += GongLiaoStation_ManualStepsConfirmChanged;
            _inspector.BanYunStation.StepsChanged += BanYunStation_StepChanged;
            _inspector.BanYunStation.CurrentFeedTrayColChanged += BanYunStation_CurrentFeedTrayColChanged;
            _inspector.BanYunStation.NozzelsProductChanged += BanYunStation_NozzelsProductChanged;
            _inspector.BanYunStation.ProductCompleted += BanYunStation_ProductCompleted;
            _inspector.BanYunStation.LiJuChanged += BanYunStation_LiJuChanged;
            _inspector.BanYunStation.ManualMESConfirmChanged += BanYunStation_ManualMESConfirmChanged;
            NGTray.Instance.NGTrayStatusChanged += NGTrayStatusChanged;
            NGTray.Instance.NGTrayItemStatusChanged += Instance_NGTrayItemStatusChanged;
            FeedTray.Instance.FeedTrayItemStatusChanged += Instance_FeedTrayItemStatusChanged;

            _inspector.SiMoStation.StepsChanged += SiMoStation_StepChanged;
            _productionLine = service.GetRequiredService<IProductionLine>();
            _productionLine.ImageDetectionResult += ProductionLine_OnImageDetectionResult;
            _autoDeleteImage.Run();
            _calcTimeService = service.GetService<ICalcTimeService>();
            _calcTimeService.OnCalcTimeChanged += CalcTimeService_OnCalcTimeChanged;
            ClearLogCommand = commandFactory.Create(ClearLog);
            ClearProductRecordCommand = commandFactory.Create(ClearProductRecord);
            ClearGongLiaoZaiJiCommand = commandFactory.Create(ClearGongLiaoZaiJi, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand1 = commandFactory.Create(ClearNozze1Status1, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand2 = commandFactory.Create(ClearNozze2Status1, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand3 = commandFactory.Create(ClearNozze3Status1, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand4 = commandFactory.Create(ClearNozze4Status1, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand5 = commandFactory.Create(ClearNozze5Status1, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand6 = commandFactory.Create(ClearNozze6Status1, () => _inspector.RunState != RunState.Running);
            ClearNozzeStatusCommand7 = commandFactory.Create(ClearNozze7Status1, () => _inspector.RunState != RunState.Running);
            ClearNGTrayCommand = commandFactory.Create(ClearNGTray, () => _inspector.RunState != RunState.Running);
            ClearFeedTrayCommand = commandFactory.Create(ClearFeedTray, () => _inspector.RunState != RunState.Running);
            ClearRunningTimeCommand = commandFactory.Create(ClearRunningTime);
            OpenLightCommand = commandFactory.Create(OpenLight);
            OpenSaveDoor1Command = commandFactory.Create(OpenSaveDoor1);
            OpenSaveDoor2Command = commandFactory.Create(OpenSaveDoor2);
            TestCommand = commandFactory.Create(Test1);
            CreateLogGroup();
            InitSeries();
            Refresh();
            CheckOperateEnable();
            _messageService = service.GetService<IMessageService>();
            _shellService = service.GetService<IShellService>();
            var _inspectorOption = optionRepository.Get<InspectorOption>();
            _runningTimeSpan = _inspectorOption.RunningTimeSpan;
            //ProductCount = _inspector.BanYunStation.Status.OKCount + _inspector.BanYunStation.Status.NGCount;
            IsDryRunMode = _inspectorOption.IsDryRunMode;
            HasFeedTray = _inspector.GongLiaoStation.Status.HasFeedTray;
            CurrentCol = _inspector.GongLiaoStation.Status.CurrentFeedTrayCol;
            NGTrayStatus = (int)NGTray.Instance.Status;
            NozzelStatus1 = _inspector.BanYunStation.Status.NozzleStatus[0];
            NozzelStatus2 = _inspector.BanYunStation.Status.NozzleStatus[1];
            NozzelStatus3 = _inspector.BanYunStation.Status.NozzleStatus[2];
            NozzelStatus4 = _inspector.BanYunStation.Status.NozzleStatus[3];
            NozzelStatus5 = _inspector.BanYunStation.Status.NozzleStatus[4];
            NozzelStatus6 = _inspector.BanYunStation.Status.NozzleStatus[5];
            NozzelStatus7 = _inspector.BanYunStation.Status.NozzleStatus[6];
            FeedTrayColunms = [.. FeedTray.Instance.FeedTrayColunms];
            NGTrayRows = [.. NGTray.Instance.NGTrayRows];
        }

        private async Task<bool> BanYunStation_ManualMESConfirmChanged(string arg)
        {
            bool state = false;
            await _dispatcher.InvokeAsync(async () =>
            {
                var dialogHost = _service.GetService<IDialogHost>();
                var confirmView = _service.GetService<IManualMESConfirmView>();
                var dialog = dialogHost.Create(confirmView);
                confirmView.WarnMessage = arg;
                await dialog.ShowDialog();
                state = confirmView.State;
            });
            return state;
        }

        private async Task<bool> GongLiaoStation_ManualStepsConfirmChanged(string arg)
        {
            bool state = false;
            await _dispatcher.InvokeAsync(async () =>
            {
                var dialogHost = _service.GetService<IDialogHost>();
                var confirmView = _service.GetService<IManualStepsConfirmView>();
                var dialog = dialogHost.Create(confirmView);
                confirmView.WarnMessage = arg;
                await dialog.ShowDialog();
                state = confirmView.State;
            });
            return state;
        }

        private void CalcTimeService_OnCalcTimeChanged(object? sender, CalcTimeEventArgs e)
        {
            _dispatcher.InvokeAsync(() =>
            {
                var option = e.Option;
                CurrentCT = option.CurrentCT;
                CurrentUPH = option.CurrentUPH;
                ProductCount = option.Sum;
                _okValue.Value = option.OK;
                _ngValue.Value = option.NG;
                RaisePropertyChanged(nameof(Yield));
            });
        }

        protected override void OnAttach()
        {
            for (int i = 1; i <= 7; i++)
            {
                LijuModels.Add(new LijuModel() { Number = i });
            }
        }

        private void BanYunStation_LiJuChanged(object? sender, IEnumerable<SiMoJi.Domain.LijuModel> e)
        {
            _dispatcher.InvokeAsync(() => LijuModels = e.ToObservableCollection());
        }

        private bool BanYunStation_FlyReadBarcoeNGChanged(string arg)
        {
            return true;
        }

        private void OpenSaveDoor2()
        {
            bool isClosed = Electronic.Default.DO10_门禁锁电源2.Value;
            if (!isClosed && _inspector.RunState != RunState.Running && !Electronic.Default.GetIsAutoRun())
            {
                Electronic.Default.DO10_门禁锁电源2.Value = false;
            }
            else if (isClosed)
            {
                Electronic.Default.DO10_门禁锁电源2.Value = true;
            }
        }

        private void OpenSaveDoor1()
        {
            bool isClosed = Electronic.Default.DO09_门禁锁电源1.Value;
            if (!isClosed && _inspector.RunState != RunState.Running && !Electronic.Default.GetIsAutoRun())
            {
                Electronic.Default.DO09_门禁锁电源1.Value = false;
            }
            else if (isClosed)
            {
                Electronic.Default.DO09_门禁锁电源1.Value = true;
            }
        }

        private async void Test1()
        {
            await BanYunStation_ManualMESConfirmChanged("进站：\r\n 125464555OK\r\n12141212121NG\r\n12141212121NG\r\n12141212121NG\r\n12141212121NG\r\n12141212121NG\r\n12141212121NG");
            //_dispatcher.Invoke(() =>
            //{
            //    if (FeedTrayColunms[1].Items[1].Status == TrayPointStatus.CompletedOK)
            //        FeedTrayColunms[1].Items[1].Status = TrayPointStatus.NG;
            //    else
            //        FeedTrayColunms[1].Items[1].Status = TrayPointStatus.CompletedOK;
            //    if (NGTrayRows[1].Items[1].Status == TrayPointStatus.CompletedOK)
            //        NGTrayRows[1].Items[1].Status = TrayPointStatus.NG;
            //    else
            //        NGTrayRows[1].Items[1].Status = TrayPointStatus.CompletedOK;

            //});
        }

        private void BanYunStation_ProductCompleted(object? sender, (bool isOK, int count) e)
        {
            _calcTimeService.CalcQuality(e.isOK ? Quality.Ok : Quality.Ng, e.count);
            //if (e.isOK)
            //{
            //    _okValue.Value += e.count;
            //}
            //else
            //{
            //    _ngValue.Value += e.count;
            //}
            //ProductCount = (int)(_okValue.Value + _ngValue.Value);
            //RaisePropertyChanged(nameof(Yield));
        }

        private void ClearRunningTime()
        {
            var _inspectorOption = _optionRepository.Get<InspectorOption>();
            _inspectorOption.RunningTimeSpan = _runningTimeSpan = TimeSpan.Zero;
            _optionRepository.Set(_inspectorOption);
            _optionRepository.SaveAsync();
        }

        private void Inspector_StatusChanged(object? sender, PartStateChangedEventArgs e)
        {
            var _inspectorOption = _optionRepository.Get<InspectorOption>();
            if (_inspectorOption.IsDryRunMode)
            {
                if (e.CurrentState == RunState.Running)
                {
                    _startRunningTime = DateTime.Now;
                }
                else if (e.CurrentState == RunState.Stop)
                {
                    var ts = DateTime.Now - _startRunningTime;
                    _runningTimeSpan += ts;
                    _inspectorOption.RunningTimeSpan = _runningTimeSpan;
                    _optionRepository.Set(_inspectorOption);
                    _optionRepository.SaveAsync();
                }
            }
            CheckOperateEnable();
        }

        private void Inspector_ManualAutoStateChanged(object sender, ManualAutoStateChangedEventArgs e)
        {
            IsManualMode = e.State == EquipmentManualAutoState.Manual;
            CheckOperateEnable();
        }

        private void CurrentUser_UserChanged(object sender, UserChangedEventArgs e)
        {
            CheckOperateEnable();
        }

        private void CheckOperateEnable()
        {
            IsSetFeedTrayEnable = _currentUser.IsGranted(PermissionProvider.SetFeedTrayEnable);
            HasHomeviewOprateRight = _currentUser.IsGranted(PermissionProvider.HomeViewOperateEnable);
            if (_inspector.RunState != RunState.Running && IsManualMode && HasHomeviewOprateRight && !Electronic.Default.GetIsAutoRun())
            {
                IsOperateEnable = true;
            }
            else
            {
                IsOperateEnable = false;
            }
        }

        private void Instance_FeedTrayItemStatusChanged(object? sender, (int colIndex, int rowIndwx, TrayPointStatus status) e)
        {
            _dispatcher.Invoke(() =>
            {
                FeedTrayColunms[e.colIndex - 1].Items[e.rowIndwx - 1].Status = e.status;
            });
        }

        private void Instance_NGTrayItemStatusChanged(object? sender, (int row, int col, TrayPointStatus status) e)
        {
            _dispatcher.Invoke(() =>
            {
                NGTrayRows[e.row - 1].Items[e.col - 1].Status = e.status;
            });
        }

        private void NGTrayStatusChanged(object? sender, NGTrayStatus e)
        {
            NGTrayStatus = (int)e;
            //var trayPoint = TrayPointStatus.OK;
            //if (e == SiMoJi.Domain.Electronics.NGTrayStatus.Disable)
            //{
            //    trayPoint = TrayPointStatus.CompletedNG;
            //}
            //else if (e == SiMoJi.Domain.Electronics.NGTrayStatus.Enable)
            //{
            //    trayPoint = TrayPointStatus.Empty;
            //}
            //else if (e == SiMoJi.Domain.Electronics.NGTrayStatus.Full)
            //{
            //    trayPoint = TrayPointStatus.CompletedNG;
            //}
            //foreach (var row in NGTrayRows)
            //{
            //    foreach (var item in row.Items)
            //    {
            //        item.Status = trayPoint;
            //    }
            //}
        }

        private void BanYunStation_NozzelsProductChanged(object? sender, TrayPointStatus[] e)
        {
            NozzelStatus1 = e[0];
            NozzelStatus2 = e[1];
            NozzelStatus3 = e[2];
            NozzelStatus4 = e[3];
            NozzelStatus5 = e[4];
            NozzelStatus6 = e[5];
            NozzelStatus7 = e[6];
        }

        private void BanYunStation_CurrentFeedTrayColChanged(object? sender, int e)
        {
            CurrentCol = e;
        }

        private void OpenLight()
        {
            var isOn = Electronic.Default.DO22_日光灯继电器.Value;
            Electronic.Default.DO22_日光灯继电器.Value = !isOn;
            IsLightOn = !isOn;
        }

        private void ClearFeedTray()
        {
            if (CurrentCol < 1)
            {
                _messageService.ShowQuestion(_shellService.ShellWindow, "设置当前列数必须大于0");
                return;
            }
            //if (CurrentCol == 1)
            //{
            //    FeedTrayColunms.ForEach(x => x.Reset());
            //}
            _inspector.BanYunStation.Status.CurrentFeedTrayCol = CurrentCol;
            _inspector.BanYunStation.Status.Save();
        }

        private void ClearNGTray()
        {
            //if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理NG料盘"))
            //{
            foreach (var ngTrayRow in NGTray.Instance.NGTrayRows)
            {
                foreach (var ngTrayRowItem in ngTrayRow.Items)
                {
                    ngTrayRowItem.IsExist = false;
                    ngTrayRowItem.Status = TrayPointStatus.Empty;
                }
            }
            NGTray.Instance.SetDisable();
            foreach (var item in NGTrayRows)
            {
                foreach (var row in item.Items)
                {
                    row.Status = TrayPointStatus.Empty;
                }
            }
            _inspector.BanYunStation.Status.Save();
            //}
        }

        public void GongLiaoStation_StepChanged(object? sender, string step)
        {
            GongLiaoStep = step;
            HasFeedTray = _inspector.GongLiaoStation.Status.HasFeedTray;
            if (hasFeedTray == false)//供料盘在籍已清除
            {
                _dispatcher.InvokeAsync(() => FeedTrayColunms.ForEach(x => x.Reset()));
            }
        }

        public void BanYunStation_StepChanged(object? sender, string step)
        {
            BanYunStep = step;
        }

        public void SiMoStation_StepChanged(object? sender, string step)
        {
            SiMoStep = step;
        }

        private TrayPointStatus SetNozzelStatus(int index)
        {
            var exist = _inspector.BanYunStation.Status.NozzleStatus[index] != TrayPointStatus.Empty;
            var status = exist ? TrayPointStatus.Empty : TrayPointStatus.OK;
            _inspector.BanYunStation.Status.NozzleStatus[index] = status;
            _inspector.BanYunStation.Status.Save();
            return status;
        }

        private void ClearNozze1Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus1 = SetNozzelStatus(0);
            }
        }
        private void ClearNozze2Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus2 = SetNozzelStatus(1);
            }
        }
        private void ClearNozze3Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus3 = SetNozzelStatus(2);
            }
        }
        private void ClearNozze4Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus4 = SetNozzelStatus(3);
            }
        }
        private void ClearNozze5Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus5 = SetNozzelStatus(4);
            }
        }
        private void ClearNozze6Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus6 = SetNozzelStatus(5);
            }
        }
        private void ClearNozze7Status1()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理产品在籍"))
            {
                NozzelStatus7 = SetNozzelStatus(6);
            }
        }
        private void ClearGongLiaoZaiJi()
        {
            if ((bool)_messageService.ShowYesNoQuestion(_shellService.ShellWindow, "是否清理料盘在籍"))
            {
                HasFeedTray = !HasFeedTray;
                _inspector.GongLiaoStation.Status.HasFeedTray = HasFeedTray;
                SignalPanel.Signal.FeedTrayReady = HasFeedTray;
                if (!HasFeedTray)
                {
                    _inspector.BanYunStation.Status.CurrentFeedTrayCol = 1;
                    _inspector.BanYunStation.Status.Save();
                }
                else
                {

                }
                _inspector.GongLiaoStation.Status.Save();
            }
        }

        private void ProductionLine_OnImageDetectionResult(object? sender, (string name, ImageDetectionResult result) e)
        {
            //ImageDetectionResult = e.result;
            _dispatcher.InvokeAsync(() =>
            {
                var result = Results.FirstOrDefault(x => x.Name == e.name);
                if (result != null)
                {
                    result.Result = e.result;
                }
                else
                {
                    var mode = new ImageResultMode(e.name, e.result);
                    Results.Add(mode);
                    SelectedImageResultModle ??= mode;
                }
            });

        }

        async void ClearProductRecord()
        {
            await _calcTimeService.Zero();
        }

        private void CreateLogGroup()
        {
            var logGroups = new List<LogGroup>();
            foreach (var item in LoggerCategory.Categories)
            {
                logGroups.Add(new LogGroup(item.Value, item.Key));
            }
            LogGroups = logGroups;
        }

        private void ClearLog()
        {
            _dispatcher.Invoke(() =>
            {
                foreach (var item in LogGroups.Select(x => x.Category))
                {
                    _applicationLog.Get(item).Clear();
                }
            });
        }

        public void Refresh()
        {
            _refreshCts?.Cancel();
            _refreshCts = new CancellationTokenSource();
            Task.Factory.StartNew(async () =>
            {
                while (!_refreshCts.IsCancellationRequested)
                {
                    await Task.Delay(500);
                    IsFeed1Ready = _inspector.Feeder1.CheckIsReady();
                    IsFeed2Ready = _inspector.Feeder2.CheckIsReady();
                    IsDoor1Closed = Electronic.Default.DI09_门禁报警信号1.Value;
                    IsDoor2Closed = Electronic.Default.DI10_门禁报警信号2.Value;
                    if (IsDryRunMode && _inspector.RunState == RunState.Running)
                    {
                        var ts = DateTime.Now - _startRunningTime;
                        var timeSpan = _runningTimeSpan + ts;
                        RunTimeRecord = $"{timeSpan.Hours}:{timeSpan.Minutes}:{timeSpan.Seconds}";
                    }
                    _eqpRunningStateModel.Refresh();
                }
            }, TaskCreationOptions.LongRunning);
        }

        private void InitSeries()
        {
            _calcTimeService.Load();
            YieldSeries = new SeriesCollection()
            {
                new PieSeries
                {
                    Title = "OK",
                    Values = new ChartValues<ObservableValue> { _okValue },
                    DataLabels = true,
                    Fill =Brushes.LimeGreen,
                    FontSize= 16,
                    Foreground= Brushes.Black
                },
                new PieSeries
                {
                    Title = "NG",
                    Values = new ChartValues<ObservableValue> { _ngValue },
                    DataLabels = true,
                    Fill = Brushes.Crimson,
                    FontSize= 16,
                    Foreground= Brushes.Black
                }
            };
        }
    }

    [AddINotifyPropertyChangedInterface]
    public class ImageResultMode
    {
        public string Name { get; set; }
        public ImageDetectionResult Result { get; set; }
        public ImageResultMode(string name, ImageDetectionResult result)
        {
            Name = name;
            Result = result;
        }
    }
}
